//
//  IAAInfoMsgVC.m
//  iPadAuditAuthorise
//
//  Created by XiangDongMBP on 16/9/2.
//  Copyright © 2016年 XiangDong. All rights reserved.
//

#import "IAAInfoMsgVC.h"
#import "IAAInfoMsgHeaderTView.h"
#import "IAAMarketDetailVC.h"
#import "IAARiskMonitorInfoVC.h"
#import "IAARiskMonitorAlarmVC.h"
#import <MJRefresh.h>
#import "IAAInfoMsgModel.h"

@interface IAAInfoMsgVC ()<UITableViewDelegate, UITableViewDataSource>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IAAInfoMsgModel *model;

@end

static NSInteger const kPageSize = 15;  //!< 每次请求的记录数
static NSString * const reuseCellId = @"UITableViewCell";
static NSString * const reuseHeaderId = @"IAAInfoMsgHeaderTView";

@implementation IAAInfoMsgVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //设置导航栏
    [self initNavigationBar];
    //設置子Views
    [self initSubViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)initNavigationBar {
    self.navigationItem.title = @"历史信息通知";
}

- (void)initSubViews {
    [self.tableView registerClass:[IAAInfoMsgHeaderTView class] forHeaderFooterViewReuseIdentifier:reuseHeaderId];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:reuseCellId];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestInfoMsg)];
    
    // 开始请求
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - <UITableViewDelegate>代理
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 45;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    IAAInfoMsgHeaderTView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:reuseHeaderId];
//    [view configViewWithCnt:8 section:section];
    IAAInfoMsgItem *item = self.model.infoMsgList[section];
    [view configViewWithCnt:item.count title:item.infoType section:section];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    IAAInfoMsgItem *item = self.model.infoMsgList[indexPath.section];
    IAAInfoMsgDetailItem *deta = item.detailList[indexPath.row];
    if (indexPath.row == item.detailList.count) {
        [self requestInfoMsgMore:indexPath.section];
        return;
    }
    
    if ([item.infoType isEqualToString:@"营销识别信息"]) { //根据文字来判断
        if (indexPath.row < item.detailList.count) {
            IAAMarketDetailVC * vc = [[IAAMarketDetailVC alloc] init];
            vc.infoNo = deta.infoNo;
//            vc.busiId = deta.recordId;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else if ([item.infoType isEqualToString:@"风险预警信息"]) {
        if (indexPath.row < item.detailList.count) {
            IAARiskMonitorInfoVC * vc = [[IAARiskMonitorInfoVC alloc] initWithType:IAARiskMonitorTypeAlarm];
            vc.infoNo = deta.infoNo;
//            vc.busiId = deta.recordId;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - <UITableViewDataSource>代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.model.infoMsgList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    IAAInfoMsgItem *item = self.model.infoMsgList[section];
    if (item.detailList.count < item.count) {
        return item.detailList.count + 1;
    } else {
        return item.detailList.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseCellId forIndexPath:indexPath];
    IAAInfoMsgItem *item;
    if (indexPath.section < self.model.infoMsgList.count) {
        item = self.model.infoMsgList[indexPath.section];
        if (indexPath.row < item.detailList.count) {
            IAAInfoMsgDetailItem *deta = item.detailList[indexPath.row];
            NSString *str = [NSString stringWithFormat:@"设备编号%@:%@", deta.deviceNo, deta.infoMsg];
            cell.textLabel.text = str;
            cell.textLabel.textAlignment = NSTextAlignmentLeft;
        } else if (indexPath.row == item.detailList.count) {
            cell.textLabel.text = @"加载更多>>";
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
        }
    }
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.textColor = IAA_COLOR_0x474646(1.0);
    if ([item.infoType isEqualToString:@"营销识别信息"] || [item.infoType isEqualToString:@"风险预警信息"]) {
        if (indexPath.row == item.detailList.count) {
            cell.accessoryType = UITableViewCellAccessoryNone;
        } else {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    } else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    return cell;
}

#pragma mark - 服务器请求数据
- (void)requestInfoMsg {
    NSString *urlStr = [IAAUrlProtocolMerge appInfoMsgList];
    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
                           @"token" : IAA_APP_DELEGATE.token,
                           @"osName": @"iOS",
                           @"startIndex" : @(0),
                           @"pageSize": @(kPageSize)};
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"历史信息通知返回：%@", responseObject);
        self.model = [IAAInfoMsgModel yy_modelWithJSON:responseObject];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"历史信息通知失败：%@", error);
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestInfoMsgMore:(NSInteger)section {
    IAAInfoMsgItem *item = self.model.infoMsgList[section];
    IAAInfoMsgDetailItem * detailItem = [item.detailList lastObject];
    
    NSString *urlStr = [IAAUrlProtocolMerge appInfoMsgMoreList];
    NSDictionary *pars = @{@"orgNo"  : IAA_APP_DELEGATE.organizeId,
                           @"token" : IAA_APP_DELEGATE.token,
                           @"osName": @"iOS",
                           @"startIndex" : @(item.detailList.count),
                           @"pageSize": @(kPageSize),
                           @"infoType": item.infoType,
                           @"lastId" : @(detailItem.recordId)};
    [XDAFHttpRequest POST:urlStr parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"历史信息通知更多返回：%@", responseObject);
        IAAInfoMsgItem *temp = [IAAInfoMsgItem yy_modelWithJSON:responseObject];
        temp.infoType = item.infoType;
        [self.model addMoreData:temp];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"历史信息通知更多失败：%@", error);
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

@end
